import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import TokenManager from '../auth/TokenManager';

// 定义API响应接口
export interface ApiResponse<T = any> {
  success: boolean;
  data: T;
  message?: string;
  code?: number;
}

// 创建axios实例
const httpClient: AxiosInstance = axios.create({
  baseURL: process.env.NX_API_URL || 'http://localhost:3000/api', // 使用环境变量或默认地址
  timeout: 30000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加认证令牌
httpClient.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 获取当前令牌
    const tokens = TokenManager.getCurrentTokens();
    
    // 如果令牌存在且有效，添加Authorization头
    if (tokens && TokenManager.isAccessTokenValid()) {
      config.headers = config.headers || {};
      config.headers['Authorization'] = `Bearer ${tokens.accessToken}`;
    }
    
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理令牌过期和错误
httpClient.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    return response.data;
  },
  async (error) => {
    const originalRequest = error.config;
    
    // 处理401未授权错误 - 尝试刷新令牌
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      
      // 尝试刷新访问令牌
      const refreshedTokens = TokenManager.refreshAccessToken();
      
      if (refreshedTokens) {
        // 更新请求头中的令牌并重新请求
        originalRequest.headers['Authorization'] = `Bearer ${refreshedTokens.accessToken}`;
        return httpClient(originalRequest);
      }
    }
    
    // 统一错误处理
    const errorMessage = error.response?.data?.message || error.message || '请求失败';
    
    // 可以在这里添加全局错误提示
    console.error('API请求错误:', errorMessage);
    
    return Promise.reject(error);
  }
);

export default httpClient;